import { OrderStatus, LogisticsIconMap } from '../config';
// import {
//   fetchBusinessTime,
//   fetchOrderDetail,
// } from '../../../services/order/orderDetail';
import Toast from 'tdesign-miniprogram/toast/index';
import { getAddressPromise } from '../../usercenter/address/list/util';
import requestApi from "../../../../utils/request"

Page({
  data: {
    pageLoading: true,
    order: {}, // 后台返回的原始数据
    _order: {}, // 内部使用和提供给 order-card 的数据
    storeDetail: {},
    countDownTime: null,
    addressEditable: false,
    backRefresh: false, // 用于接收其他页面back时的状态
    formatCreateTime: '', //格式化订单创建时间
    logisticsNodes: [],
    /** 订单评论状态 */
    orderHasCommented: true,
  },

  onLoad(query) {
    this.orderNo = query.orderNo;
    this.init();
    this.navbar = this.selectComponent('#navbar');
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    // 当从其他页面返回，并且 backRefresh 被置为 true 时，刷新数据
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({ backRefresh: false });
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onImgError(e) {
    if (e.detail) {
      console.error('img 加载失败');
    }
  },

  // 页面初始化，会展示pageLoading
  init() {
    this.setData({ pageLoading: true });
    this.getStoreDetail();
    this.getDetail()
    // .then(() => {
    //   this.setData({ pageLoading: false });
    // })
    // .catch((e) => {
    //   console.error(e);
    // });
  },

  // 页面刷新，展示下拉刷新
  onRefresh() {
    this.init();
    // 如果上一页为订单列表，通知其刷新数据
    const pages = getCurrentPages();
    const lastPage = pages[pages.length - 2];
    if (lastPage) {
      lastPage.data.backRefresh = true;
    }
  },

  // 页面刷新，展示下拉刷新
  onPullDownRefresh_(e) {
    const { callback } = e.detail;
    return this.getDetail().then(() => callback && callback());
  },
  timestampToDate(timestamp) {
    // 时间戳为10位需*1000，时间戳为13位不需乘1000
    var date = new Date(timestamp * 1000);
    var Y = date.getFullYear() + "-";
    var M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "-";
    var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
    var h = date.getHours() + ":";
    var m = date.getMinutes() + ":";
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
  },
  getDetail() {
    console.log(this.orderNo)
    const params = JSON.parse(this.orderNo)
    requestApi.get('shopro/order/detail', params, true).then(res => {
      const order = res.data;
      //查询物流
      if (order.status_code == 'noget') {
        requestApi.get('shopro/order_express/index', { order_id: order.id }, true).then(res => {
          if (res.code === 1) {
            this.setData({
              logisticsNodes: res.data[1].log,
            })
          }
        })
      }
      const _order = {
        id: order.id,
        orderNo: order.order_sn,
        parentOrderNo: order.parentOrderNo,
        storeId: order.storeId,
        storeName: order.storeName,
        status: order.orderStatus,
        statusDesc: order.status_desc,
        paymentAmount: order.total_fee * 100,
        totalAmount: order.total_amount * 100,
        // logisticsNo: order.logisticsVO.logisticsNo,
        goodsList: (order.item || []).map((goods) =>
          Object.assign({}, goods, {
            id: goods.id,
            thumb: goods.goods_image,
            title: goods.goods_title,
            skuId: goods.skuId,
            spuId: goods.spuId,
            specs: goods.goods_sku_text,
            price: goods.goods_price * 100, // 商品销售单价, 优先取限时活动价
            num: goods.goods_num,
            titlePrefixTags: goods.tagText ? [{ text: goods.tagText }] : [],
            buttons: goods.buttonVOs || [],
          }),
        ),
        buttons: order.buttonVOs || [],
        createTime: order.createTime,
        receiverAddress: this.composeAddress(order),
        groupInfoVo: order.groupInfoVo,
        receiverName: order.consignee,
        receiverPhone: order.phone,
        createTime: order.createtime,
        remark: order.remark
      };
      this.setData({
        order,
        _order,
        formatCreateTime: this.timestampToDate(order.createtime),
        // countDownTime: this.computeCountDownTime(order),
        // addressEditable:
        //   [OrderStatus.PENDING_PAYMENT, OrderStatus.PENDING_DELIVERY].includes(
        //     order.orderStatus,
        //   ) && order.orderSubStatus !== -1, // 订单正在取消审核时不允许修改地址（但是返回的状态码与待发货一致）
        // isPaid: !!order.paymentVO.paySuccessTime,
        // invoiceStatus: this.datermineInvoiceStatus(order),
        // invoiceDesc: order.invoiceDesc,
        // invoiceType:
        //   order.invoiceVO?.invoiceType === 5 ? '电子普通发票' : '不开发票', //是否开票 0-不开 5-电子发票
        // logisticsNodes: this.flattenNodes(order.trajectoryVos || []),
      });
    })
  },

  // 展开物流节点
  flattenNodes(nodes) {
    console.log(nodes)

    // return (nodes || []).reduce((res, node) => {
    //   return (node.log || []).reduce((res1, subNode, index) => {
    //     res1.push({
    //       title: index === 0 ? node.title : '', // 子节点中仅第一个显示title
    //       desc: subNode.status,
    //       date: formatTime(+subNode.timestamp, 'YYYY-MM-DD HH:mm:ss'),
    //       icon: index === 0 ? LogisticsIconMap[node.code] || '' : '', // 子节点中仅第一个显示icon
    //     });
    //     return res1;
    //   }, res);
    // }, []);
  },

  datermineInvoiceStatus(order) {
    // 1-已开票
    // 2-未开票（可补开）
    // 3-未开票
    // 4-门店不支持开票
    return order.invoiceStatus;
  },

  // 拼接省市区
  composeAddress(order) {
    return [
      //order.logisticsVO.receiverProvince,
      order.province_name,
      order.city_name,
      order.area_name,
      order.address,
    ]
      .filter((s) => !!s)
      .join(' ');
  },

  getStoreDetail() {
    // fetchBusinessTime().then((res) => {
    //   const storeDetail = {
    //     storeTel: res.data.telphone,
    //     storeBusiness: res.data.businessTime.join('\n'),
    //   };
    //   this.setData({ storeDetail });
    // });
  },

  // 仅对待支付状态计算付款倒计时
  // 返回时间若是大于2020.01.01，说明返回的是关闭时间，否则说明返回的直接就是剩余时间
  computeCountDownTime(order) {
    if (order.orderStatus !== OrderStatus.PENDING_PAYMENT) return null;
    return order.autoCancelTime > 1577808000000
      ? order.autoCancelTime - Date.now()
      : order.autoCancelTime;
  },

  onCountDownFinish() {
    //this.setData({ countDownTime: -1 });
    const { countDownTime, order } = this.data;
    if (
      countDownTime > 0 ||
      (order && order.groupInfoVo && order.groupInfoVo.residueTime > 0)
    ) {
      this.onRefresh();
    }
  },

  onGoodsCardTap(e) {
    const { index } = e.currentTarget.dataset;
    const goods = this.data.order.item[index];
    console.log(goods)
    wx.navigateTo({ url: `/service/shoppingMallDetails/details/index?spuId=${goods.goods_id}` });
  },

  onEditAddressTap() {
    getAddressPromise()
      .then((address) => {
        this.setData({
          'order.logisticsVO.receiverName': address.name,
          'order.logisticsVO.receiverPhone': address.phone,
          '_order.receiverAddress': address.address,
        });
      })
      .catch(() => { });

    wx.navigateTo({
      url: `/service/shoppingMall/usercenter/address/list/index?selectMode=1`,
    });
  },

  onOrderNumCopy() {
    wx.setClipboardData({
      data: this.data.order.orderNo,
    });
  },

  onDeliveryNumCopy() {
    wx.setClipboardData({
      data: this.data.order.logisticsVO.logisticsNo,
    });
  },

  onToInvoice() {
    wx.navigateTo({
      url: `/pages/order/invoice/index?orderNo=${this.data._order.orderNo}`,
    });
  },

  onSuppleMentInvoice() {
    wx.navigateTo({
      url: `/pages/order/receipt/index?orderNo=${this.data._order.orderNo}`,
    });
  },

  onDeliveryClick() {

    const { order } = this.data
    const logisticsData = {
      order_id: order.id//订单ID
    };
    wx.navigateTo({
      url: `/service/shoppingMall/Order/delivery-detail/index?data=${JSON.stringify(logisticsData)}`,
    });
  },

  /** 跳转订单评价 */
  navToCommentCreate() {
    wx.navigateTo({
      url: `/pages/order/createComment/index?orderNo=${this.orderNo}`,
    });
  },

  /** 跳转拼团详情/分享页*/
  toGrouponDetail() {
    wx.showToast({ title: '点击了拼团' });
  },

  clickService() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '您点击了联系客服',
    });
  },

  onOrderInvoiceView() {
    wx.navigateTo({
      url: `/pages/order/invoice/index?orderNo=${this.orderNo}`,
    });
  },
});
